import { baseUrl } from '@/common/config'
import { useUserStore } from '@/stores'

interface ApiResult<T> {
  code: number
  message: string
  data: T
}

const showToast = (title: string) => {
  uni.showToast({
    title,
    icon: 'none',
    duration: 3000
  })
}

const showMessage = (title: unknown) => {
  console.log(title)
  const message = JSON.stringify(title).replace(/"/g, '')
  if (message.indexOf('Network') > -1) {
    showToast('请求失败，请联系客服')
  } else if (message.indexOf('timeout') > -1) {
    showToast('请求超时')
  } else {
    showToast(message)
  }
}

uni.addInterceptor('request', {
  invoke(args) {
    // 请求拦截
    if (!args.url.startsWith('http')) {
      args.url = baseUrl() + args.url
    }
    const token = useUserStore().token
    if (token) {
      args.header = {
        Authorization: `Bearer ${token}`
      }
    }
  }
})

function request<T>(options: UniApp.RequestOptions) {
  return new Promise<T>((resolve, reject) => {
    uni.request({
      ...options,
      success: (res) => {
        const { statusCode, errMsg, data: result } = res
        if (statusCode !== 200) {
          showToast(errMsg!)
        } else {
          const { code, message, data } = result as ApiResult<T>
          switch (code) {
            case 0:
              resolve(data)
              break
            case 401:
              //useUserStore().login()
              reject(result)
              break
            case 100030:
              uni.showModal({
                title: '提示',
                content: message,
                showCancel: false,
                success() {
                  uni.navigateBack()
                }
              })
              break
            default:
              showToast(message)
              reject(result)
              break
          }
        }
      },
      fail: (err) => {
        showMessage(err)
        reject(err)
      }
    })
  })
}

export default async function http<T>(options: UniApp.RequestOptions) {
  return await request<T>(options)
}
